package com.fwj.auth.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fwj.auth.model.AuthUser;
import com.fwj.auth.util.AuthenticationStoreUtil;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: fwj
 * @Data: 2022/4/13 15:09
 * @Version 1.0
 * @Description:
 */
public class CommonAuthFilter extends UsernamePasswordAuthenticationFilter {

    /**
     * 空字符串
     */
    private final String EMPTY = "";


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        //如果不是JSON格式使用自带的过滤器获取参数，就是form表单
        if (!request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE) && !request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            String username = this.obtainUsername(request);
            String password = this.obtainPassword(request);
            storeAuthentication(username, password);
            Authentication authentication = super.attemptAuthentication(request, response);
            return authentication;
        }

        //如果是JSON请求使用取参数逻辑
        ObjectMapper mapper = new ObjectMapper();
        UsernamePasswordAuthenticationToken authRequest = null;
        try (InputStream is = request.getInputStream()) {
            AuthUser user = mapper.readValue(is, AuthUser.class);
            storeAuthentication(user.getAccount(), user.getPassword());
            authRequest = new UsernamePasswordAuthenticationToken(user.getAccount(), user.getPassword());
        } catch (IOException e) {
            e.printStackTrace();
            authRequest = new UsernamePasswordAuthenticationToken(EMPTY, EMPTY);
        } finally {
            setDetails(request, authRequest);
            Authentication authenticate = this.getAuthenticationManager().authenticate(authRequest);
            return authenticate;
        }
    }

    /**
     * 保存用户名和密码
     * @param username 帐号:邮箱/手机号
     * @param password 密码
     */
    private void storeAuthentication(String username, String password) {
        AuthenticationStoreUtil.setUsername(username);
        AuthenticationStoreUtil.setPassword(password);
    }
}
